package com.cy.store.controller;

import com.cy.store.service.ICartService;
import com.cy.store.util.JsonResult;
import com.cy.store.vo.CartVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/carts")
public class CartController extends BaseController {

    @Autowired
    private ICartService cartService;

    @RequestMapping("/add_to_cart")
    public JsonResult<Void> addToCart(Integer pid, Integer amount, HttpSession session) {
        cartService.addToCart(getUidFromSession(session), pid, amount, getUsernameFromSession(session));
        return new JsonResult<>(OK);
    }

    @RequestMapping({"", "/"})
    public JsonResult<List<CartVo>> getVOByUid(HttpSession session) {
        Integer uid = getUidFromSession(session);
        List<CartVo> list = cartService.getVOByUid(uid);
        return new JsonResult<>(OK, list);
    }

    @RequestMapping("/num_add/{cid}")
    public JsonResult<Integer> addNum(@PathVariable("cid") Integer cid, String ope, HttpSession session) {
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        Integer num = cartService.addNum(cid, ope, uid, username);
        return new JsonResult<>(OK, num);
    }

    @RequestMapping("/delete")
    public JsonResult<Void> deleteByCids(Integer[] cids, HttpSession session) {
        Integer uid = getUidFromSession(session);
        cartService.deleteCart(uid, cids);
        return new JsonResult<>(OK);
    }

    @RequestMapping("/list")
    public JsonResult<List<CartVo>> getVOByCid(Integer[] cids, HttpSession session) {
        Integer uid = getUidFromSession(session);
        String username = getUsernameFromSession(session);
        List<CartVo> list = cartService.getVOByCid(uid, cids);
        return new JsonResult<>(OK, list);
    }
}
